package com.imooc.service.impl;

import com.imooc.bo.UpdatedUserBO;
import com.imooc.enums.Sex;
import com.imooc.enums.UserInfoModifyType;
import com.imooc.enums.YesOrNo;
import com.imooc.exceptions.GraceException;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import com.imooc.service.UserService;
import com.imooc.util.DateUtil;
import com.imooc.util.DesensitizationUtil;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @ClasName UserServiceImpl
 * @Descripution TODO
 * @Author leikw
 * @Date 2023/2/10 20:46
 * @Version V1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    Sid sid;

    private final String USER_FACE1 = "https://emos-1305179729.cos.ap-nanjing.myqcloud.com/img/header/bda13361b4bc04ac29d8a98e50b79faf.jpeg";

    /**
     * @Author leikw
     * @Description // 根据手机号查询用户
     * @Date  2023/2/10 21:04
     */
    @Override
    public Users queryMobileIsExist(String mobile) {
        Example userExample = new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("mobile", mobile);

        return usersMapper.selectOneByExample(userExample);
    }

    /**
     * @Author leikw
     * @Description //创建用户信息并返回
     * @Date  2023/2/10 21:05
     */
    @Override
    @Transactional
    public Users createUser(String mobile) {

        // 获得全局唯一主键
        String userId = sid.nextShort();

        Users user = new Users();
        user.setId(userId);

        user.setMobile(mobile);
        user.setNickname("用户：" + DesensitizationUtil.commonDisplay(mobile));
        user.setImoocNum("用户：" + DesensitizationUtil.commonDisplay(mobile));
        user.setFace(USER_FACE1);

        user.setBirthday(DateUtil.stringToDate("1900-01-01"));
        user.setSex(Sex.secret.type);

        user.setCountry("中国");
        user.setProvince("");
        user.setCity("");
        user.setDistrict("");
        user.setDescription("这家伙很懒，什么都没留下~");
        user.setCanImoocNumBeUpdated(YesOrNo.YES.type);

        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        usersMapper.insert(user);

        return user;
    }

    /**
     * @Author leikw
     * @Description 根据主键查询用户信息
     * @Date  2023/2/11 15:33
     */
    @Override
    public Users getUser(String userId) {
        return usersMapper.selectByPrimaryKey(userId);
    }

    /**
     * @Author leikw
     * @Description 用户信息修改
     * @Date  2023/2/11 16:05
     */
    @Override
    @Transactional
    public Users updateUserInfo(UpdatedUserBO updatedUserBO) {
        Users users = new Users();
        BeanUtils.copyProperties(updatedUserBO,users);
        int rows = usersMapper.updateByPrimaryKeySelective(users);
        if(rows != 1){
            GraceException.display(ResponseStatusEnum.USER_UPDATE_ERROR);
        }
        return getUser(users.getId());
    }

    /**
     * @Author leikw
     * @Description 修改用户信息  根据修改字段不同做不同的判断与操作
     * @Date  2023/2/11 16:08
     */
    @Override
    @Transactional
    public Users updateUserInfo(UpdatedUserBO updatedUserBO, Integer type) {
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();

        //修改NICKNAME时判断是否已经存在
        if (type == UserInfoModifyType.NICKNAME.type) {
            criteria.andEqualTo("nickname", updatedUserBO.getNickname());
            Users user = usersMapper.selectOneByExample(example);
            if (user != null) {
                GraceException.display(ResponseStatusEnum.USER_INFO_UPDATED_NICKNAME_EXIST_ERROR);
            }
        }

        //修改imoocNum
        if (type == UserInfoModifyType.IMOOCNUM.type) {
            //修改imoocNum时判断是否已经存在
            criteria.andEqualTo("imoocNum", updatedUserBO.getImoocNum());
            Users user = usersMapper.selectOneByExample(example);
            if (user != null) {
                GraceException.display(ResponseStatusEnum.USER_INFO_UPDATED_NICKNAME_EXIST_ERROR);
            }

            //修改imoocNum时判断是否可以修改
            Users tempUser =  getUser(updatedUserBO.getId());
            if (tempUser.getCanImoocNumBeUpdated() == YesOrNo.NO.type) {
                GraceException.display(ResponseStatusEnum.USER_INFO_CANT_UPDATED_IMOOCNUM_ERROR);
            }
            //可修改时设置属性（只可修改一次）
            updatedUserBO.setCanImoocNumBeUpdated(YesOrNo.NO.type);
        }

        return updateUserInfo(updatedUserBO);
    }
}
